var express = require('express');
var db = require('./mongodb/db.js');
var redis = require('./redis/index.js');
var config = require('./config/config.js');
var router = require('./routes/index.js');
var bodyParser = require('body-parser') // express post数据必须引入
var cookieParser = require('cookie-parser')
var session = require('express-session');
var path = require('path');
var ejs = require('ejs')


const app = express();


//启用session 和 cookie
app.use(cookieParser())
app.use(session({
    secret: '!ffgwregwg34$%$', //用于生成sessionid
    name: 'wkf',
    cookie: { maxAge: 8000000 },
    resave: false,
    saveUninitialized: true,
}));

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials", true); //可以带cookies

    

    res.header("X-Powered-By", 'xs')
    if (req.method == 'OPTIONS') {
        res.send(200);
    } else {
        next();
    }
});

app.all('/admin/*',function(req,res,next){
	var sessionAdmin = req.session.admin;

    if (!sessionAdmin) {
    	res.redirect('/login');
    }else{
    	next();
    }
})

app.engine('html', ejs.__express);
app.set('views', path.join(__dirname, 'views/'))
app.set('view engine', 'html')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router)
app.use('/static', express.static('./static'));
app.listen(config.port);